﻿using System.ClientModel;
using OpenAI;
using OpenAI.Chat;

namespace OpenAiWrapper.API.Services
{
    public class OpenAiService : IOpenAiService
    {
        public async Task<string> GetChatCompletionAsync(
            string apiKey,
            string question,
            string apiUrl = "https://api.openai.com"
        )
        {
            var keyCredential = new ApiKeyCredential(apiKey);
            var clientOptions = new OpenAIClientOptions()
            {
                Endpoint = new Uri(apiUrl)
            };
            var client = new ChatClient("gpt-3.5-turbo", keyCredential, clientOptions);
            ChatCompletion completion = await client.CompleteChatAsync(ChatMessage.CreateUserMessage(question));
            return completion.Content[0].Text;
        }

        public async Task<string> GetChatCompletionAsync(
            string apiKey,
            string question,
            string model,
            string apiUrl
        )
        {
            var keyCredential = new ApiKeyCredential(apiKey);
            var clientOptions = new OpenAIClientOptions()
            {
                Endpoint = new Uri(apiUrl)
            };
            var client = new ChatClient(model, keyCredential, clientOptions);
            var completion = await client.CompleteChatAsync(ChatMessage.CreateUserMessage(question));
            return completion.Value.Content[0].Text;
        }
    }
}
